> >I have a question for the following snip C program.
>
> >typedef struct item {
> > int val;
> > struct item *next;
> >} ITEM, *PITEM;
>
> >main()
> >{
> > PITEM head, current;
> > head=(PITEM) malloc(sizeof(ITEM));
> > ^^^^^^^
> > head->val=1;
> >}
>
> >I want to know why need to use the type casting PITEM in front of the
> >malloc ? Please help!
>
> Simple answer: You don't have to use that cast, and you should _not_ use
> it, because all you can do with that cast is _hide_ an error.Error?!? Why do you think that casting is an error? The standard ANSI runtime library says:
...
malloc Function
Syntax
#include <stdlib.h>
void *malloc(size_t size);
Description
The 'malloc' function allocates an amount of memory that equals to 'size'.
Return values
The 'malloc' function returns a NULL pointer if it fails, otherwise it returns
a 'void' pointer to the allocated memory area.
...
So, if he needs to use that pointer returned by malloc function he have to convert it from a 'void' pointer to a 'item' pointer ( PITEM ).
Many compilers don't need the use of casting. It's only a good programming style. But remember: malloc returns a 'void' pointer because it doesn't know wich
kind of data you'll store in the allocated mem block!
>
> OTOH, if you are using a C++ compiler to translate C programs, the cast
> is needed, but malloc() is obsolete.
> C++ compilers are more rigorous! But if you write a strict-ANSI C program a c++ compiler won't return any error...